package de.guice.aktenschrank.messenger;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import com.google.inject.Singleton;

import de.guice.aktenschrank.configuration.Annotation.Trace;


@Singleton
public class EMailImpl implements Messenger {

	private final static String USERNAME = "guice@omegavision.lu";
	private final static String PASSWORT = "verysecret";
	private final static String HOST = "mail.omegavision.lu";
	private final static String PORT = "587";
	private final static String TO = "philippe.mitsch@gmail.com";
	private final static String FROM = "guice@omegavision.lu";
	
	private final static String SUBJECT = "[Guice Mailer] Notification";
	private final static Integer MAX_MSG = 1;
	
	private Integer counter = 0;
	
	@Override
	@Trace("Sending E-Mail")
	public void sendNotification(Notification notification) throws Throwable {

		String msg = "E-Mail notification Nr " + (counter + 1) + ": " + notification.getMessage() + " Time: "+notification.getDate().toString();

		try {
			if (counter <= MAX_MSG)	{
				counter++;
				run(SUBJECT, msg);
			}
		} catch (MessagingException e) {
			throw new Throwable(e.toString());
		}
	}
	
	private void run(String subject, String body) throws MessagingException {
		Message message = new MimeMessage(getSession());

		message.addRecipient(RecipientType.TO, new InternetAddress(TO));
		message.addFrom(new InternetAddress[] { new InternetAddress(FROM) });

		message.setSubject(subject);
		message.setContent(body, "text/plain");

		Transport.send(message);
	}

	private Session getSession() {
		Authenticator authenticator = new Authenticator();

		Properties properties = new Properties();
		properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
		properties.setProperty("mail.smtp.auth", "true");

		properties.setProperty("mail.smtp.host", HOST);
		properties.setProperty("mail.smtp.port", PORT);

		return Session.getInstance(properties, authenticator);
	}

	private class Authenticator extends javax.mail.Authenticator {
		private PasswordAuthentication authentication;

		public Authenticator() {
			authentication = new PasswordAuthentication(USERNAME, PASSWORT);
		}

		protected PasswordAuthentication getPasswordAuthentication() {
			return authentication;
		}
	}
}
